package http

import (
	"bufio"
	"go2/log"
	pool2 "go2/pool"
	"io"
	"net"
	"net/http"
	"time"
)

func handleHTTPTunnel(writer io.Writer, reader *bufio.Reader, req *http.Request) {
	// 使用带超时的连接
	dialer := &net.Dialer{
		Timeout:   30 * time.Second,
		KeepAlive: 30 * time.Second,
	}

	target, err := dialer.Dial("tcp", req.Host)
	if err != nil {
		writer.Write([]byte("HTTP/1.1 502 Bad Gateway\r\n\r\n"))
		return
	}
	defer target.Close()

	log.Debugf("handleHTTPTunnel %s", target.RemoteAddr().String())

	writer.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n"))

	// 使用更大的缓冲区提升大文件传输性能
	buf1 := pool2.Malloc(1024 * 1024) // 64KB缓冲区提升吞吐量
	defer pool2.Free(buf1)
	buf2 := pool2.Malloc(1024 * 1024) // 64KB缓冲区提升吞吐量
	defer pool2.Free(buf2)

	go io.CopyBuffer(target, reader, buf1)
	io.CopyBuffer(writer, target, buf2)
}

func (proxy *ProxyHttpServer) Serve(conn io.Writer, reader *bufio.Reader) {
	req, err := http.ReadRequest(reader)
	if err != nil {
		//log.Errorf("Failed to read HTTP request: %s", err.Error())
		return
	}

	// 	proxy.ServeHTTP(NewResponse2(conn, 1), req)

	if req.Method == http.MethodConnect {
		handleHTTPTunnel(conn, reader, req)
	} else {
		proxy.handleHttp(NewResponse2(conn, 1), req)
	}
}
